﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace redis_study
{
    class Interlock1
    {
        //记录线程数
        private static int threadCount = 0;
        private static Random rnd = new Random();

        /// <summary>
        /// 创建一个线程，什么事也不干， 只随机停留1~12秒
        /// </summary>
        private static void RndThreadFunc()
        {
            //新建线程，线程数加一
            Interlocked.Increment(ref threadCount);

            try
            {
                //什么事也不干， 只随机停留1~12秒
                int sleepTime = rnd.Next(1000, 12000);
                Thread.Sleep(sleepTime);
            }
            finally
            {
                //线程结束，线程数减一
                Interlocked.Decrement(ref threadCount);
            }
        }

        /// <summary>
        /// 每隔一秒，通报有几个线程存在
        /// </summary>
        private static void RptThread()
        {
            while (true)
            {
                int threadNumber = 0;
                //获取当前线程数
                threadNumber = Interlocked.Exchange(ref threadCount, threadCount);
                Console.WriteLine("{0} Thread(s) alive ", threadNumber);
                //休眠1秒
                Thread.Sleep(1000);
            }
        }

        public static void Run()
        {
            //创建RptThread线程，每隔一秒通报有几个线程存在
            Thread reporter = new Thread(new ThreadStart(RptThread));
            //设置为后台线程
            reporter.IsBackground = true;
            reporter.Start();

            //创建50个RndThreadFunc线程
            Thread[] rndThreads = new Thread[50];
            for (int i = 0; i < 50; i++)
            {
                rndThreads[i] = new Thread(new ThreadStart(RndThreadFunc));
                rndThreads[i].Start();
            }
        }
    }
}
